#include "cpu_scheduler.h"
#include <QProcess>
#include <QFile>
#include <QStandardPaths>
#include <QDir>
#include <QMessageBox>
#include <QApplication>
#include <QTextStream>
#include <QDateTime>
#include <QDebug>

CpuScheduler::CpuScheduler(QObject *parent)
    : QObject(parent)
{
    // 初始化默认配置
    m_config.checkInterval = 10;
    m_config.highFreqThreshold = 80;
    m_config.lowFreqThreshold = 40;
    m_config.highTempThreshold = 60;
    m_config.lowTempThreshold = 40;
    m_config.sustainedPeriod = 60;
    m_config.freqReduction = 25;
    m_config.freqIncrease = 25;
    m_config.minFreqLimit = 50;
    m_config.enableTempControl = true;
    m_config.enableFreqControl = true;
    m_config.logFile = "/var/log/cpu-scheduler.log";
    m_config.configFile = "/etc/cpu-scheduler.conf";
}

CpuScheduler::~CpuScheduler()
{
}

bool CpuScheduler::createService()
{
    // 创建配置文件
    if (!createConfigFile()) {
        return false;
    }
    
    // 创建服务文件
    if (!createServiceFile()) {
        return false;
    }
    
    // 重载systemd配置
    QProcess process;
    process.start("systemctl", QStringList() << "daemon-reload");
    process.waitForFinished();
    
    if (process.exitCode() != 0) {
        qWarning() << "Failed to reload systemd daemon:" << process.readAllStandardError();
        return false;
    }
    
    // 启用服务
    process.start("systemctl", QStringList() << "enable" << "cpu-scheduler.service");
    process.waitForFinished();
    
    if (process.exitCode() != 0) {
        qWarning() << "Failed to enable cpu-scheduler service:" << process.readAllStandardError();
        return false;
    }
    
    qDebug() << "CPU调度优化服务已创建";
    return true;
}

bool CpuScheduler::createConfigFile()
{
    QString configContent = QString(
        "# CPU调度优化配置文件\n"
        "[DEFAULT]\n"
        "CHECK_INTERVAL = %1\n"
        "HIGH_FREQ_THRESHOLD = %2\n"
        "LOW_FREQ_THRESHOLD = %3\n"
        "HIGH_TEMP_THRESHOLD = %4\n"
        "LOW_TEMP_THRESHOLD = %5\n"
        "SUSTAINED_PERIOD = %6\n"
        "FREQ_REDUCTION = %7\n"
        "FREQ_INCREASE = %8\n"
        "MIN_FREQ_LIMIT = %9\n"
        "LOG_FILE = %10\n"
        "ENABLE_TEMP_CONTROL = %11\n"
        "ENABLE_FREQ_CONTROL = %12\n"
    ).arg(m_config.checkInterval)
     .arg(m_config.highFreqThreshold)
     .arg(m_config.lowFreqThreshold)
     .arg(m_config.highTempThreshold)
     .arg(m_config.lowTempThreshold)
     .arg(m_config.sustainedPeriod)
     .arg(m_config.freqReduction)
     .arg(m_config.freqIncrease)
     .arg(m_config.minFreqLimit)
     .arg(m_config.logFile)
     .arg(m_config.enableTempControl ? "true" : "false")
     .arg(m_config.enableFreqControl ? "true" : "false");
    
    QFile file(m_config.configFile);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法创建配置文件:" << m_config.configFile;
        return false;
    }
    
    QTextStream out(&file);
    out << configContent;
    file.close();
    
    return true;
}

bool CpuScheduler::createServiceFile()
{
    QString serviceContent = QString(
        "[Unit]\n"
        "Description=CPU Scheduler Service\n"
        "After=network.target\n"
        "\n"
        "[Service]\n"
        "Type=simple\n"
        "ExecStart=%1 --service\n"
        "Restart=always\n"
        "RestartSec=10\n"
        "\n"
        "[Install]\n"
        "WantedBy=multi-user.target\n"
    ).arg(QDir(QApplication::applicationDirPath()).absoluteFilePath("cpu_scheduler"));
    
    QFile file("/etc/systemd/system/cpu-scheduler.service");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法创建服务文件: /etc/systemd/system/cpu-scheduler.service";
        return false;
    }
    
    QTextStream out(&file);
    out << serviceContent;
    file.close();
    
    return true;
}

bool CpuScheduler::isServiceActive()
{
    QProcess process;
    process.start("systemctl", QStringList() << "is-active" << "cpu-scheduler.service");
    process.waitForFinished();
    
    QString status = process.readAllStandardOutput().trimmed();
    return (status == "active");
}

bool CpuScheduler::startService()
{
    QProcess process;
    process.start("systemctl", QStringList() << "start" << "cpu-scheduler.service");
    process.waitForFinished();
    
    return (process.exitCode() == 0);
}

bool CpuScheduler::stopService()
{
    QProcess process;
    process.start("systemctl", QStringList() << "stop" << "cpu-scheduler.service");
    process.waitForFinished();
    
    return (process.exitCode() == 0);
}

bool CpuScheduler::resetCpuFrequency()
{
    // 恢复CPU最大频率的实现
    // 这里需要根据实际系统路径进行调整
    QStringList cpuPaths;
    QDir cpuDir("/sys/devices/system/cpu/");
    QStringList cpuDirs = cpuDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    
    for (const QString &dir : cpuDirs) {
        if (dir.startsWith("cpu") && dir.length() > 3 && dir.mid(3).toInt() >= 0) {
            QString scalingMaxFreqPath = QString("/sys/devices/system/cpu/%1/cpufreq/scaling_max_freq").arg(dir);
            QString cpuinfoMaxFreqPath = QString("/sys/devices/system/cpu/%1/cpufreq/cpuinfo_max_freq").arg(dir);
            
            if (QFile::exists(cpuinfoMaxFreqPath) && QFile::exists(scalingMaxFreqPath)) {
                QFile maxFreqFile(cpuinfoMaxFreqPath);
                if (maxFreqFile.open(QIODevice::ReadOnly)) {
                    QString maxFreqStr = maxFreqFile.readAll().trimmed();
                    maxFreqFile.close();
                    
                    QFile scalingFile(scalingMaxFreqPath);
                    if (scalingFile.open(QIODevice::WriteOnly)) {
                        scalingFile.write(maxFreqStr.toUtf8());
                        scalingFile.close();
                    }
                }
            }
        }
    }
    
    return true;
}

void CpuScheduler::setConfig(const SchedulerConfig &config)
{
    m_config = config;
}

SchedulerConfig CpuScheduler::getConfig() const
{
    return m_config;
}